import pprint
import logging
import traceback

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to
from pylons.decorators.rest import restrict

from sc_console.lib.base import BaseController, render

from sc_console.model.models import ErrorReport, RawMessage
from sc_console.model.meta import Session

from advanced_json_encoding import encode

log = logging.getLogger(__name__)

class ErrorReportController(BaseController):
    def index(self):
        c.errors = Session.query(ErrorReport)\
                .order_by(ErrorReport.time.desc()).all()
        return render('/error_report/index.mako')

    def view(self):
        id = request.urlvars['id']
        c.error = Session.query(ErrorReport).filter(ErrorReport.id == id).first()
        c.rendered_data = pprint.pformat(c.error.message_data)
        c.rendered_traceback = '\n'.join(traceback.format_list(c.error.traceback))

        c.rendered_log_entries = []
        formatter = logging.Formatter(logging.BASIC_FORMAT)
        for log_record in c.error.log:
            c.rendered_log_entries.append(formatter.format(log_record))

        return render('/error_report/view.mako')

    @restrict('POST')
    def retry(self):
        id = request.urlvars['id']

        error = Session.query(ErrorReport).filter(ErrorReport.id == id).first()
        rm = RawMessage(message_name=error.message_name,  data=error.message_data)

        Session.add(rm)
        Session.delete(error)
        Session.commit()


    @restrict('POST')
    def delete(self):
        id = request.urlvars['id']
        error = Session.query(ErrorReport).filter(ErrorReport.id == id).first()

        Session.delete(error)

        Session.commit()

